package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.entity.WorkStatistics;
import com.rickpan.service.WorkStatisticsService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 工作统计控制器
 * 提供工作数据的统计分析接口
 */
@RestController
@RequestMapping("/api/work-statistics")
@Tag(name = "工作统计", description = "工作数据统计分析相关接口")
public class WorkStatisticsController {

    private static final Logger logger = LoggerFactory.getLogger(WorkStatisticsController.class);

    @Autowired
    private WorkStatisticsService workStatisticsService;

    /**
     * 获取用户统计数据概览
     */
    @GetMapping("/overview")
    @Operation(summary = "获取统计概览", description = "获取用户工作数据的统计概览")
    public ApiResponse<Map<String, Object>> getStatisticsOverview() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Map<String, Object> overview = workStatisticsService.getUserStatisticsOverview(userId);
            return ApiResponse.success(overview);
        } catch (Exception e) {
            logger.error("获取统计概览失败", e);
            return ApiResponse.error("获取统计概览失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户工作趋势数据
     */
    @GetMapping("/trends")
    @Operation(summary = "获取工作趋势", description = "获取用户工作数据的趋势分析")
    public ApiResponse<Map<String, Object>> getWorkTrends(
            @Parameter(description = "时间周期") @RequestParam(defaultValue = "daily") String period) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Map<String, Object> trends = workStatisticsService.getUserWorkTrends(userId, period);
            return ApiResponse.success(trends);
        } catch (Exception e) {
            logger.error("获取工作趋势失败", e);
            return ApiResponse.error("获取工作趋势失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类统计汇总
     */
    @GetMapping("/category-summary")
    @Operation(summary = "获取分类统计", description = "获取用户工作记录的分类统计汇总")
    public ApiResponse<Map<String, Integer>> getCategoryStatsSummary() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Map<String, Integer> summary = workStatisticsService.getUserCategoryStatsSummary(userId);
            return ApiResponse.success(summary);
        } catch (Exception e) {
            logger.error("获取分类统计失败", e);
            return ApiResponse.error("获取分类统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取优先级统计汇总
     */
    @GetMapping("/priority-summary")
    @Operation(summary = "获取优先级统计", description = "获取用户工作记录的优先级统计汇总")
    public ApiResponse<Map<String, Integer>> getPriorityStatsSummary() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Map<String, Integer> summary = workStatisticsService.getUserPriorityStatsSummary(userId);
            return ApiResponse.success(summary);
        } catch (Exception e) {
            logger.error("获取优先级统计失败", e);
            return ApiResponse.error("获取优先级统计失败: " + e.getMessage());
        }
    }

    /**
     * 生成指定日期的日统计数据
     */
    @PostMapping("/generate/daily")
    @Operation(summary = "生成日统计", description = "生成指定日期的日统计数据")
    public ApiResponse<WorkStatistics> generateDailyStatistics(
            @Parameter(description = "统计日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            WorkStatistics statistics = workStatisticsService.generateDailyStatistics(userId, date);
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            logger.error("生成日统计失败，日期: {}", date, e);
            return ApiResponse.error("生成日统计失败: " + e.getMessage());
        }
    }

    /**
     * 生成指定周的周统计数据
     */
    @PostMapping("/generate/weekly")
    @Operation(summary = "生成周统计", description = "生成指定周的周统计数据")
    public ApiResponse<WorkStatistics> generateWeeklyStatistics(
            @Parameter(description = "周开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate weekStart) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            WorkStatistics statistics = workStatisticsService.generateWeeklyStatistics(userId, weekStart);
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            logger.error("生成周统计失败，周开始: {}", weekStart, e);
            return ApiResponse.error("生成周统计失败: " + e.getMessage());
        }
    }

    /**
     * 生成指定月的月统计数据
     */
    @PostMapping("/generate/monthly")
    @Operation(summary = "生成月统计", description = "生成指定月的月统计数据")
    public ApiResponse<WorkStatistics> generateMonthlyStatistics(
            @Parameter(description = "月开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate monthStart) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            WorkStatistics statistics = workStatisticsService.generateMonthlyStatistics(userId, monthStart);
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            logger.error("生成月统计失败，月开始: {}", monthStart, e);
            return ApiResponse.error("生成月统计失败: " + e.getMessage());
        }
    }

    /**
     * 批量生成缺失的统计数据
     */
    @PostMapping("/generate/missing")
    @Operation(summary = "生成缺失统计", description = "批量生成用户缺失的统计数据")
    public ApiResponse<Void> generateMissingStatistics() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            workStatisticsService.generateMissingStatistics(userId);
            return ApiResponse.<Void>success("缺失统计数据生成成功");
        } catch (Exception e) {
            logger.error("生成缺失统计数据失败", e);
            return ApiResponse.error("生成缺失统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户效率分析报告
     */
    @GetMapping("/efficiency-report")
    @Operation(summary = "获取效率报告", description = "获取用户工作效率分析报告")
    public ApiResponse<Map<String, Object>> getEfficiencyReport(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 如果没有指定日期范围，默认使用最近30天
            if (startDate == null) {
                startDate = LocalDate.now().minusDays(30);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            Map<String, Object> report = new HashMap<>();
            
            // 获取基础统计概览
            Map<String, Object> overview = workStatisticsService.getUserStatisticsOverview(userId);
            report.put("overview", overview);
            
            // 获取趋势数据
            Map<String, Object> trends = workStatisticsService.getUserWorkTrends(userId, "daily");
            report.put("trends", trends);
            
            // 获取分类统计
            Map<String, Integer> categoryStats = workStatisticsService.getUserCategoryStatsSummary(userId);
            report.put("categoryStats", categoryStats);
            
            // 获取优先级统计
            Map<String, Integer> priorityStats = workStatisticsService.getUserPriorityStatsSummary(userId);
            report.put("priorityStats", priorityStats);
            
            // 添加时间范围信息
            report.put("dateRange", Map.of("startDate", startDate, "endDate", endDate));
            
            return ApiResponse.success(report);
        } catch (Exception e) {
            logger.error("获取效率报告失败", e);
            return ApiResponse.error("获取效率报告失败: " + e.getMessage());
        }
    }

    /**
     * 获取工作负载分析
     */
    @GetMapping("/workload-analysis")
    @Operation(summary = "获取工作负载分析", description = "获取用户工作负载的详细分析")
    public ApiResponse<Map<String, Object>> getWorkloadAnalysis(
            @Parameter(description = "分析周期") @RequestParam(defaultValue = "week") String period) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            Map<String, Object> analysis = new HashMap<>();

            // 获取趋势数据
            Map<String, Object> trends = workStatisticsService.getUserWorkTrends(userId, period);
            analysis.put("trends", trends);

            // 获取统计概览
            Map<String, Object> overview = workStatisticsService.getUserStatisticsOverview(userId);
            analysis.put("overview", overview);

            // 计算工作负载指标
            Double avgEfficiency = (Double) overview.get("avgEfficiencyScore");
            Long totalRecords = (Long) overview.get("totalRecords");
            Long totalTime = (Long) overview.get("totalTimeSpent");

            Map<String, Object> workloadMetrics = new HashMap<>();
            workloadMetrics.put("avgEfficiency", avgEfficiency);
            workloadMetrics.put("totalRecords", totalRecords);
            workloadMetrics.put("totalTime", totalTime);
            workloadMetrics.put("avgTimePerRecord", totalRecords > 0 ? (double) totalTime / totalRecords : 0);

            analysis.put("workloadMetrics", workloadMetrics);

            return ApiResponse.success(analysis);
        } catch (Exception e) {
            logger.error("获取工作负载分析失败", e);
            return ApiResponse.error("获取工作负载分析失败: " + e.getMessage());
        }
    }


}
